import { getToken, setToken, getUid, setUid, removeToken, removeUid } from '@/utils/auth'
import { Message } from 'element-ui'
import API from '@/api/axios'
import { componentMap } from '@/utils/routeComponentMap'

const state = {
  uid: getUid(), // 用户id
  token: getToken(), // token
  roles: [], // 用户的角色列表
  uroutes: [], // 从后台获取用户可访问的路由列表
  finalURoutes: [], // 当前用户最终可以访问的路由列表（uRoutes + constRutes）
  perms: [] // 当前用户角色的权限
}

const mutations = {
  SET_UID (state, uid) {
    state.uid = uid
  },
  SET_TOKEN (state, token) {
    state.token = token
  },
  SET_ROLES (state, roles) {
    state.roles = roles
  },
  SET_UROUTES (state, uroutes) {
    state.uroutes = uroutes
  },
  SET_FINALUROUTES (state, routes) {
    state.finalURoutes = routes
  },
  SET_PERMS (state, perms) {
    state.perms = perms
  }
}

const actions = {
  // 登录
  async login ({ commit }, userInfo) {
    const res = await API({ name: 'login', data: userInfo })
    if (res.data.code === 200) {
      commit('SET_UID', res.data.data)
      commit('SET_TOKEN', res.data.token)
      setUid(res.data.data)
      setToken(res.data.token)
    } else {
      Message.error({ message: res.data.msg  || 'Has Error' })
    }
    return res
  },
  // 获取用户的角色信息
  async getUserinfo ({ commit }) {
    const res = await API({ name: 'detailUser', paths: [getUid()], requireAuth: true })
    if (res.data.code === 200) {
      commit('SET_ROLES', res.data.data.ur)
    } else {
      Message.error({ message: res.data.msg  || 'Has Error' })
    }
    return res.data.data.ur
  },
  // 获取角色的路由权限信息 -> 将菜单转换为路由格式
  async getURoutes ({ commit }) {
    const res = await API({ name: 'getUserMenu', paths: [getUid()], requireAuth: true })
    const routes = []
    if (res.data.code === 200) {
      // 先一层一层遍历
      res.data.data.sort((a, b) => a.order - b.order).forEach(item1 => {
        // 第一层
        let temp1 = {
          path: item1.path,
          name: item1.component,
          component: componentMap[item1.component],
          children: [],
          meta: {
            title: item1.name,
            icon: item1.icon,
            is_frame: item1.is_frame,
            hidden: item1.visible
          }
        }
        if (item1.children) {
          item1.children.sort((a, b) => a.order - b.order).forEach(item2 => {
            // 第二层
            let temp2 = {
              path: item2.path,
              name: item2.component,
              component: componentMap[item2.component],
              children: [],
              meta: {
                title: item2.name,
                icon: item2.icon,
                is_frame: item2.is_frame,
                hidden: item2.visible,
                activeMenu: item2.visible === 1 ? '' : temp1.path
              }
            }
            if (item2.children) {
              item2.children.sort((a, b) => a.order - b.order).forEach(item3 => {
                // 第三层
                let temp3 = {
                  path: item3.path,
                  name: item3.component,
                  component: componentMap[item3.component],
                  children: [],
                  meta: {
                    title: item3.name,
                    icon: item3.icon,
                    is_frame: item3.is_frame,
                    hidden: item3.visible,
                    activeMenu: item3.visible === 1 ? '' : temp2.path
                  }
                }
                if (item3.children) {
                  item3.children.sort((a, b) => a.order - b.order).forEach(item4 => {
                    // 第四层
                    let temp4 = {
                      path: item4.path,
                      name: item4.component,
                      component: componentMap[item4.component],
                      children: [],
                      meta: {
                        title: item4.name,
                        icon: item4.icon,
                        is_frame: item4.is_frame,
                        hidden: item4.visible,
                        activeMenu: item4.visible === 1 ? '' : temp3.path
                      }
                    }
                    item3.children.push(temp4)
                  })
                }
                temp2.children.push(temp3)
              })
              const redirect = item2.children.filter(item => item.visible === 1)[0]
              if (redirect) {
                temp2.redirect = redirect.path
              }
            }
            temp1.children.push(temp2)
          })
          const redirect = item1.children.filter(item => item.visible === 1)[0]
          if (redirect) {
            temp1.redirect = redirect.path
          }
        }
        routes.push(temp1)
      })
      commit('SET_UROUTES', routes)
    } else {
      Message.error({ message: res.data.msg  || 'Has Error' })
    }
    return routes
  },
  // 设置用户最终路由
  setFinalURoutes ({ commit }, routes) {
    commit('SET_FINALUROUTES', routes)
  },
  // 获取用户角色的权限
  async getPerms ({ commit }, roleId) {
    const res = await API({ name: 'detailRole', paths: [roleId], requireAuth: true })
    if (res.data.code === 200) {
      commit('SET_PERMS', res.data.data.rp)
    } else {
      Message.error({ message: res.data.msg  || 'Has Error' })
    }
    return res.data.data.rp
  },
  // 清除信息
  removeInfo ({ commit }) {
    commit('SET_UID', '')
    commit('SET_TOKEN', '')
    commit('SET_ROLES', [])
    removeToken()
    removeUid()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}